package com.github.controller;

import com.github.bean.CallLog;
import com.github.bean.UserStatus;
import com.github.service.CallLogServer;
import lombok.Data;
import org.aspectj.weaver.ast.Call;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/call-records")
public class CallRecordController {
    @Autowired
    CallLogServer callLogServer;

    // 查询通话记录
    @PostMapping
    public Map<String, Object> getCallRecords(@RequestBody RequestBodyWrapper request) {
        String account = request.getAccount();
        // 获取所有在线用户
        List<CallLog> callLogs = callLogServer.getCallLogByAccount(account);
        callLogs.sort(Comparator.comparingLong(
                user -> user.getStart_time() != null ? user.getStart_time() : Long.MAX_VALUE
        ));
        // 分页处理
        int start = request.page * request.size;
        int end = Math.min(start + request.size, callLogs.size());
        List<CallLog> pageUsers = callLogs.subList(start, end);
        // 构造分页对象
        Page<CallLog> userPage = new PageImpl<>(pageUsers, PageRequest.of(request.page, request.size), callLogs.size());
        // 构造返回数据
        Map<String, Object> response = new HashMap<>();
        response.put("content", userPage.getContent());
        response.put("totalPages", userPage.getTotalPages());
        response.put("totalElements", userPage.getTotalElements());

        return response;
    }

    // 清空通话记录
    @PostMapping("/clear")
    public ApiResponse clearCallRecords(@RequestBody RequestBodyWrapper request) {
        String account = request.getAccount();
        boolean removed = callLogServer.delCallLogByAccount(account);
        if (removed) {
            return new ApiResponse("success", "通话记录已清空！");
        } else {
            return new ApiResponse("error", "未找到相关通话记录！");
        }
    }

    // 接收 POST 请求的通用包装类
    @Data
    public static class RequestBodyWrapper {
        private int page = 0;
        private int size = 10;
        private String account;
    }

    // 统一返回格式
    @Data
    public static class ApiResponse {
        private String status;
        private String message;

        public ApiResponse(String status, String message) {
            this.status = status;
            this.message = message;
        }
    }
}